import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from '@vant/auto-import-resolver';
import postcssPxToRem from 'postcss-pxtorem';

const pathResolve = (dir: string) => {
	return resolve(__dirname, '.', dir);
};

const alias: Record<string, string> = {
	'/@': pathResolve('./src/'),
};

// https://vitejs.dev/config/
const viteConfig = defineConfig((mode) => {
	const env = loadEnv(mode.mode, process.cwd());
	return {
		plugins: [
			vue(),
			AutoImport({
				imports: ['vue', 'vue-router', 'pinia'],
				dts: './auto-imports.d.ts',
				resolvers: [VantResolver()],
			}),
			Components({
				resolvers: [VantResolver()],
			}),
		],
		resolve: { alias },
		base: './',
		server: {
			host: '0.0.0.0', // 服务器地址
			port: env.VITE_PORT as unknown as number, // 服务器端口号
			open: env.VITE_OPEN === 'true', // 是否自动打开浏览器
			hmr: true, // 启用热更新
			proxy: {
				'/api': {
					// target: 'http://irs.dcg-hami.dev.dcginner:10003/api', //测试环境
					target: 'http://irs-gateway.dcg-hami.dev.dcginner:10003/',
					// target: 'http://sanji.dcg-hami.test.dcginner:10006/api',
					ws: true, // 是否启用 WebSocket
					changeOrigin: true, // 是否修改请求头中的 Origin 字段
					rewrite: (path) => path.replace(/^\/api/, ''),
				},
				'/api/admin': {
					//单体架构下特殊处理代码生成模块代理
					target: 'http://192.168.5.88:4000/', // 李洋
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/api\/admin/, ''),
				},
			},
		},
		build: {
			sourcemap: false,
			outDir: 'dist', // 打包输出目录
			chunkSizeWarningLimit: 1500, // 代码分包阈值
			rollupOptions: {
				output: {
					entryFileNames: `assets/[name].[hash].js`,
					chunkFileNames: `assets/[name].[hash].js`,
					assetFileNames: `assets/[name].[hash].[ext]`,
					compact: true,
					manualChunks: {
						vue: ['vue', 'vue-router', 'pinia'],
					},
				},
			},
		},
		css: {
			preprocessorOptions: { css: { charset: false } },
			postcss: {
				plugins: [
					postcssPxToRem({
						rootValue({ file }: any) {
							// return file.indexOf('van') !== -1 ? 37.5 : 37.5
							return file.indexOf('vant') !== -1 ? 37.5 : 37.5;
						},
						// 需要转换的单位，默认是 px
						propList: ['*'],
						// 允许转换媒体查询中的 px
						mediaQuery: false,
						replace: true,
						// 需要忽略的选择器，保留 px 单位
						selectorBlackList: ['ignore'],
						// 最小的转换单位，小于这个值不转换
						minPixelValue: 2,
						// 转换后保留的小数位数
						unitPrecision: 5,
						// 排除 node_modules 中的文件
						exclude: '/node_modules/i',
					}),
				],
			},
		},
		define: {
			__INTLIFY_PROD_DEVTOOLS__: JSON.stringify(false),
			__VERSION__: JSON.stringify(process.env.npm_package_version),
			__NEXT_NAME__: JSON.stringify(process.env.npm_package_name),
		},
	};
});

export default viteConfig;
